正規表現を使ってadd dateのCodeLensを作る処理
https://github.com/vscodejp/handson-hello-vscode-extension/blob/main/docs/beginner/04_edit.md
code:3. ドキュメントを解析して、CodeLens を表示しよう より.ts
while ((matches = regex.exec(text)) !== null) {
// 見出しが見つかった行を抽出し、
// その範囲をレンジとして切り出す
const line = document.lineAt(document.positionAt(matches.index).line);
const indexOf = line.text.indexOf(matches0);
const position = new vscode.Position(line.lineNumber, indexOf);
const range = document.getWordRangeAtPosition(
position,
new RegExp(titleRegex)
);
if (range) {
// この範囲に対するCodeLensを作成する
codeLenses.push(
new vscode.CodeLens(range, {
title: "add date",
tooltip: "add date",
})
);
}
}
lineの取り出し
matches.indexは文字列の位置(整数)(RegExpのexecメソッド)
vscode.TextDocument.positionAt
TextDocumentの中でmatches.indexのvscode.Positionを返す
改行文字が改行として見える状態ではなく、ひとつながりの文字列としてindexが"何行目何文字目か"
vscode.TextDocument.lineAt
position.lineを使って行(vscode.TextLine)を取得(変数に抽出する余地あり)
indexOfを取得=マッチした文字列(matches[0])がlineの何文字目から始まるか
StringのindexOf
position(vscode.Position)を作成:マッチした文字列の行のindexOfの位置
(カーソルを置ける位置のような理解)
positionからtitleRegexに一致するrangeを取得
vscode.TextDocument.getWordRangeAtPosition
rangeはundefinedになりうるからif文
これで# sの行の# が取得できる!
感想:rangeの取得はけっこう大変な処理
rangeを使ってCodeLensを作る
rangeにコマンドを結びつけ